define(function(require) {

    'use strict';

    var Backbone = require('backbone'),
        Base = require('components/pop/base'),
        template = require('text!components/pop/templates/import.html'),
        utils = require('core/utils'),
        _ = require('underscore');

    require('components/validation/validate');

    require('select2');

    var Model = Backbone.Model.extend({
        validation: {
            min_retail_price: function(value) {
                value = +value;
                if (_.isNaN(value) || value <= 0) {
                    return '最小零售价必须是数字';
                }
                if (value > this.get('max_retail_price')) {
                    return '最小零售价大于最大零售价';
                }
            },
            max_retail_price: function(value) {
                value = +value;
                if ( _.isNaN(value) || value <= 0) {
                    return '最大零售价必须是数字';
                }
            },
            fx_price: function(value) {
                if (value <= 0) {
                    return '分销价格必须大于 0';
                }
            },
            delivery_template_id: {
                required: true,
                msg: '请选择一个运费模板'
            }
        }
    });

    return Base.extend({

        template: _.template(template),

        className: 'popover left popover-import',

        events: {
            'click .js-btn-cancel': 'hide',
            'click .js-btn-confirm:not([disabled=true])': 'triggerCallback'
        },

        initialize: function(options) {
            Base.prototype.initialize.call(this, options);
            this.data = options.data;
            this.model = new Model();
            this.setGoodsId();
        },

        setGoodsId: function() {
            this.model.set('kdt_goods_id', this.data.goodsId);
        },

        render: function() {
            var view = this;

            this.$el.html(this.template(this.data));
            view.price = view.$el.find('.js-price');
            view.sellMinPrice = view.$el.find('.js-sell-min-price');
            view.sellMaxPrice = view.$el.find('.js-sell-max-price');
            view.deliveryTpl = view.$el.find('.js-delivery-template');

            view.initDeliveryTemplate();

            Backbone.Validation.bind(this);
            return view;
        },

        reset: function(obj) {
            var callback = obj.callback,
                target = obj.target,
                trigger = obj.trigger,
                className = obj.className || 'popover left',
                data = obj.data;

            this.options.className = className;
            this.setCallback(callback);
            this.setTarget(target);
            this.setTrigger(trigger);
            this.clearInput();
            this.setData(data);
            this.positioning();
            this.setDeliveryTemplate('0');
            this.fetchDeliveryData();
            this.show();
        },

        positioning: function() {
            var view = this;

            var className = view.options.className;

            view.$el.show();
            if (className.indexOf('left') !== -1) {
                view.$el.position({
                    of: view.target,
                    my: 'right center',
                    at: 'left center',
                    collision: 'none'
                });
            } else if(className.indexOf('bottom') !== -1) {
                view.$el.position({
                    of: view.target,
                    my: 'center top',
                    at: 'center bottom',
                    collision: 'none'
                });
            } else {
                view.$el.position({
                    of: view.target,
                    my: 'left center',
                    at: 'right center',
                    collision: 'none'
                });
            }

            view.el.className = view.options.className;
        },

        clearInput: function() {
            var view = this;

            view.price.val('');
            view.sellMinPrice.val('');
            view.sellMaxPrice.val('');
        },

        setData: function(data) {
            this.data = data;
            this.setGoodsId();
        },

        triggerCallback: function(e) {
            var view = this;

            var arrData = this.$('form').serializeArray();
            _.each(arrData, function(obj) {
                view.model.set(obj.name, obj.value);
            });
            var flag = view.model.validate();
            if (flag) {
                return;
            }
            var $tar = $(e.target);
            $tar.button('loading');
            var formData = view.model.toJSON();
            utils.ajax(_global.url.fenxiao + '/supplier/goods/import.json', {
                type: 'POST',
                data: formData
            }).done(function(data) {
                utils.successNotify('导入成功');
                view.callback(formData);
                view.hide();
            }).fail(function(msg) {
                utils.errorNotify(msg);
            }).always(function() {
                $tar.button('reset');
            });
        },

        setDeliveryTemplate: function(tplId) {
            var view = this;

            view.deliveryTpl.select2('val', tplId);
            view.model.set('delivery_template_id', tplId);
        },

        fetchDeliveryData: function() {
            var view = this;

            if (view.isFetching) {
                return false;
            }

            view.isFetching = true;
            var url = window._global.url.fenxiao + '/trade/delivery/idToNameMap.json';
            utils.ajax({
                url: url,
                method: 'GET',
            }).done(function(data) {
                view.processDeliveryData(data);
            }).fail(function(msg) {
                utils.errorNotify(msg);
            }).always(function() {
                view.isFetching = false;
            });
        },

        processDeliveryData: function(data) {
            var view = this;

            var array = [];
            _(data).each(function(value, key) {
                array.push({
                    id: key,
                    text: value
                });
            });
            var config = view.getSelect2Config(array);
            view.initDeliverySelect2(config);
        },

        initDeliverySelect2: function(config) {
            var view = this;

            view.deliveryTpl.select2('destroy');
            view.deliveryTpl.select2(config)
                .on('select2-opening', function(event) {})
                .on('select2-selecting', function(event) {
                    var data = event.object;
                    view.selectDeliveryTemplate(data, event);
                });
        },

        getSelect2Config: function(data) {
            var view = this;

            var config = {
                multiple: false,
                maximumInputLength: 12,
                width: 219,
                data: data
            };
            config.placeholder = _.isEmpty(data) ? '没有可用运费模板': '请选择运费模版...';

            return config;
        },

        initDeliveryTemplate: function() {
            var view = this;

            view.deliveryData = [];
            view.fetchDeliveryData();
        },

        selectDeliveryTemplate: function(data, event) {
            var view = this;

            var tplId = data.id;
            view.model.set('delivery_template_id', tplId);
        }
    });
});
